package p.ithorns.intergration.hz.client;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IExecutorService;
import com.hazelcast.map.IMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import p.ithorns.integration.hz.core.SumTask;

import javax.annotation.PostConstruct;

/**
 * HazelcastService
 * TODO ithorns
 *
 * @author Ht.L
 * @date 2023-11-21 09:14
 * @since 1.0.0
 */
@Service
public class HazelcastService {

    @Autowired
    private transient HazelcastInstance hz;

    IExecutorService exe;

    @PostConstruct
    public synchronized void init() {
        this.exe = hz.getExecutorService("EXE");
        IMap<String, Integer> map = hz.getMap("map");
        map.put(key, 0);
    }

    private final String key = "K";

    public void submitAndCalculateSum(int number) {
        // 使用EntryProcessor执行，用以优化Map.put & Map.set步骤
        // map.executeOnEntries(new SumEntryProcessor());

        // 定义Task Callable 或者 Runnable
        SumTask task = new SumTask(number);

        // member选择器： 在hazelcast.xml中定义<member-attributes>
        // <member-attributes>
        //    <attribute name="type">worker</attribute>
        // </member-attributes>
        // 如下代码会提交到所有定义过<attribute name="type">worker</attribute>的节点上执行
        exe.submit(task, member -> "worker".equals(member.getAttribute("type")));

        // 不同于submit, submitToMembers会提交给所有符合条件的节点
        // exe.submitToMembers(task, member -> )
    }

}